/*
 * Created on Jan 13, 2007
 *
 * Publishes clipboard images to a public website, launches the image 
 * in the user's default Internet browser where the user can 
 * drag and drop the image link into a GMail message. 
 * 
 */
package com.pla.clipboardimagepublisher;

import java.awt.Component;
import java.awt.Cursor;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.prefs.Preferences;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.awt.datatransfer.StringSelection;

public class ClipboardImagePublisherGUI extends JFrame implements ActionListener, WindowListener,
    ClipboardOwner {
  private static final long serialVersionUID = 1783149207192290834L;
  private JPanel panel;
  private final String FILE = "File";
  private final String QUIT = "Quit";
  private final String ABOUT = "About";
  private static ClassLoader classLoader = ClipboardImagePublisherGUI.class.getClassLoader();
  private Preferences preferences;
  private final String PUBLISH_WEB = "Publish web";
  private final String PUBLISH_LOCAL = "Publish local";
  private final String DONE = "Done";
  private final String EDIT = "Edit";
  private final String SETTINGS = "Settings";
  private ClipboardImagePublisher cip;

  public static void main(String[] args) {
    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    }
    catch (Exception e) {
      System.out.println("Error setting native LAF: " + e);
    }
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        new ClipboardImagePublisherGUI();
      }
    });
  }

  public ClipboardImagePublisherGUI() {
    super("Clipboard Image Publisher");
    preferences = Preferences.userNodeForPackage(this.getClass());
    addWindowListener(this);
    createGUI();
    pack();
    int x = preferences.getInt("x", 0);
    int y = preferences.getInt("y", 0);
    setLocation(x, y);
    int width = preferences.getInt("width", this.getWidth());
    int height = preferences.getInt("height", this.getHeight());
    setSize(width, height);
    setVisible(true);
    cip = new ClipboardImagePublisher();
  }

  private void createGUI() {
    setJMenuBar(createMenuBar());
    setIconImage(getIcon("clipboard_next48x48.png").getImage());
    panel = new JPanel();
    getContentPane().add(panel);
    panel.add(createButton(EDIT));
    panel.add(createButton(PUBLISH_WEB));
    panel.add(createButton(PUBLISH_LOCAL));
    panel.add(createButton(QUIT));
  }

  private JButton createButton(String text) {
    JButton button = new JButton(text);
    button.addActionListener(this);
    button.setActionCommand(text);
    return button;
  }

  private JMenuItem createMenuItem(String name) {
    JMenuItem menuItem = new JMenuItem(name);
    menuItem.addActionListener(this);
    menuItem.setActionCommand(name);
    return menuItem;
  }

  public static ImageIcon getIcon(String fileName) {
    return new ImageIcon(classLoader.getResource("resources/" + fileName));
  }

  private void savePreferences() {
    System.out.println("Saving preferences");
    Point point = getLocation();
    preferences.putInt("x", (int) point.getX());
    preferences.putInt("y", (int) point.getY());
    preferences.putInt("width", getWidth());
    preferences.putInt("height", getHeight());
  }

  private JMenuBar createMenuBar() {
    JMenuBar menuBar = new JMenuBar();
    JMenu fileMenu = new JMenu(FILE);
    fileMenu.setMnemonic(KeyEvent.VK_F);
    JMenuItem settingsMenuItem = createMenuItem(SETTINGS);
    settingsMenuItem.setActionCommand(SETTINGS);
    fileMenu.add(settingsMenuItem);
    JMenuItem quitMenuItem = createMenuItem(QUIT);
    quitMenuItem.setMnemonic(KeyEvent.VK_Q);
    quitMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
    fileMenu.add(new JSeparator());
    fileMenu.add(quitMenuItem);
    menuBar.add(fileMenu);
    JMenu helpMenu = new JMenu("Help");
    helpMenu.setMnemonic(KeyEvent.VK_H);
    JMenuItem aboutMenuItem = createMenuItem(ABOUT);
    aboutMenuItem.setMnemonic(KeyEvent.VK_A);
    helpMenu.add(aboutMenuItem);
    menuBar.add(helpMenu);
    return menuBar;
  }

  public void actionPerformed(ActionEvent e) {
    String actionCommand = e.getActionCommand();
    System.out.println("Action command: " + actionCommand);
    if (QUIT.equals(actionCommand)) {
      dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
    }
    if (ABOUT.equals(actionCommand)) {
      new AboutDialog(this);
    }
    if (SETTINGS.equals(actionCommand)) {
      new PreferencesDialog(this);
    }
    if (EDIT.equals(actionCommand)) {
      ableComponents(false);
      try {
        cip.writeLocalTemporaryFile();
        ClipboardImagePublisher.launchUrl(cip.getLocalTemporaryAbsolutePath());
      }
      catch (Exception e1) {
        JOptionPane.showMessageDialog(this, "Cannot edit. Error text: " + e1.getMessage(), "Error",
            JOptionPane.ERROR_MESSAGE);
      }
      ableComponents(true);
    }
    if (PUBLISH_LOCAL.equals(actionCommand)) {
      ableComponents(false);
      try {
        cip.writeLocalTemporaryFile();
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(new StringSelection(cip.getLocalTemporaryAbsolutePath()), this);
        JOptionPane.showMessageDialog(this, "File name copied to clipboard.", "Success",
            JOptionPane.INFORMATION_MESSAGE);
      }
      catch (Exception e1) {
        JOptionPane.showMessageDialog(this, "Cannot edit. Error text: " + e1.getMessage(), "Error",
            JOptionPane.ERROR_MESSAGE);
      }
      ableComponents(true);
    }
    if (PUBLISH_WEB.equals(actionCommand)) {
      ableComponents(false);
      String returnMessage = null;
      try {
        returnMessage = cip.publish();
        if (DONE.equals(returnMessage)) {
          String hostName = preferences.get(PreferencesDialog.HOST_NAME, "patrickarchibald.com");
          String picturePath = preferences.get(PreferencesDialog.PICTURE_PATH, "/pictures/");
          ClipboardImagePublisher.launchUrl("http://"
              + hostName
              + picturePath
              + cip.getPublishedFileName());
        }
        else {
          JOptionPane.showMessageDialog(this,
              "Image not published. The server return this message: " + returnMessage, "Error",
              JOptionPane.ERROR_MESSAGE);
        }
      }
      catch (Exception e1) {
        JOptionPane.showMessageDialog(this, "Image not published. Error text: " + e1.getMessage(),
            "Error", JOptionPane.ERROR_MESSAGE);
      }
      cip = new ClipboardImagePublisher();
      ableComponents(true);
    }
  }

  public void windowActivated(WindowEvent e) {
  }

  public void windowClosed(WindowEvent e) {
  }

  public void windowClosing(WindowEvent e) {
    System.out.print(e);
    savePreferences();
    System.exit(0);
  }

  public void windowDeactivated(WindowEvent e) {
  }

  public void windowDeiconified(WindowEvent e) {
  }

  public void windowIconified(WindowEvent e) {
  }

  public void windowOpened(WindowEvent e) {
  }

  private void ableComponents(boolean status) {
    if (status) {
      setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    }
    else {
      setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    }
    Component[] components = panel.getComponents();
    int quantity = components.length;
    for (int i = 0; i < quantity; i++) {
      components[i].setEnabled(status);
    }
  }

  public void lostOwnership(Clipboard clipboard, Transferable contents) {
  }
}
